//
// Created by denglibin on 2021/3/26.
// 绘制文字
#include <SDL.h>
#include <SDL_ttf.h>
#define WIN_WIDTH 600
#define WIN_HEIGHT 400
#define FRAME_RATE 60 //帧率
#define FONT_SIZE 32
static struct SDL_Window * win; //窗口
static struct SDL_Surface * winSurface; //窗口的surface
static TTF_Font *font;

/**
 * 事件循环
 */
static void eventLoop(){
    SDL_Event  event;
    while (1)
    {//主消息循环
        SDL_PollEvent(&event);
        if(event.type == SDL_QUIT){
            return;
        }
        uint32_t  begin = SDL_GetTicks();
        uint32_t  end = SDL_GetTicks();
        uint32_t  cost = end - begin;
        uint32_t per_frame_time = 1000 / FRAME_RATE;//每一帧耗时ms
        if (per_frame_time > cost){
            //减去循环体耗时，得到还应休眠的时间
             SDL_Delay(per_frame_time - cost);
        }
    }

}
/**
 * 初始化操作
 */
static void init(){
    if(TTF_Init()){
        SDL_Log("Can not init TTF %s\n", SDL_GetError());
        exit(1);
    }
    //初始化，成功返回0
    if (SDL_Init(SDL_INIT_VIDEO)) {
        SDL_Log("Can not init video %s\n", SDL_GetError());
        exit(1);
    }
}

/**
 * 加载字体
 */
static void loadFont(){
    font = TTF_OpenFont("font/msyh.ttc", FONT_SIZE);
    if (font == NULL){
        SDL_Log("Can not open font %s\n", SDL_GetError());
        exit(1);
    }
}

/**
 * 创建显示窗口
 * @return
 */
static int showWindow(){

    win = SDL_CreateWindow("Hello World",
                           SDL_WINDOWPOS_CENTERED,
                           SDL_WINDOWPOS_CENTERED,
                           WIN_WIDTH,
                           WIN_HEIGHT,
                           SDL_WINDOW_SHOWN
    );
    if (win == NULL) {
        SDL_Log("Can not create window %s\n", SDL_GetError());
        return 2;
    }
    winSurface = SDL_GetWindowSurface(win);

    //矩形
    struct SDL_Rect  r = {0, 0, WIN_WIDTH, WIN_HEIGHT};
    //用矩形填充winSurface
    SDL_FillRect(winSurface, &r, 0xFF00AA00);


    SDL_Color color = {255, 255, 0, 255};
    struct SDL_Surface * textSurface = TTF_RenderUTF8_Blended(font, "hello,你好!", color);
    struct SDL_Rect src = {0, 0, textSurface->w, textSurface->h};
    SDL_BlitSurface(textSurface, &src, winSurface, &src);
    SDL_FreeSurface(textSurface);//清理
    SDL_UpdateWindowSurface(win);
    return 0;

}

/**
 * 清理
 */
static void clean(){
    TTF_CloseFont(font);
    SDL_FreeSurface(winSurface);
    SDL_DestroyWindow(win);
}
int main2_8(int argc, char* argv[]){
    init();
    loadFont();
    if (showWindow()){
        exit(1);
    }
    eventLoop();
    clean();
    SDL_Quit();
}

